"""配置加载工具（解析config.yaml）"""
"""配置加载工具（解析config.yaml）"""
import os
import yaml
from typing import Dict, Any
import logging

logger = logging.getLogger(__name__)


# 统一配置加载器，支持多级配置合并和环境变量覆盖
class ConfigLoader:
    _instance = None
    _lock = False
    _config = None
    
    def __new__(cls):
        if cls._instance is None:
            if cls._lock:
                raise Exception("正在创建ConfigLoader实例，请稍后再试")
            cls._lock = True
            cls._instance = super(ConfigLoader, cls).__new__(cls)
            cls._lock = False
        return cls._instance
    
    def __init__(self):
        if not hasattr(self, '_initialized'):
            self.load_config()
            self._initialized = True

    def load_config(self, config_path: str = None) -> None:
        """
        加载配置文件
        Args:
            config_path: 配置文件路径，如果为None则使用默认路径
        """
        if config_path is None:
            # 获取当前文件所在目录
            current_dir = os.path.dirname(os.path.abspath(__file__))
            # 构建配置文件路径
            config_path = os.path.join(current_dir, 'config.yaml')

        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                self._config = yaml.safe_load(f)
            logger.info(f"配置文件加载成功: {config_path}")
        except Exception as e:
            logger.error(f"配置文件加载失败: {str(e)}")
            raise

    def get_config(self) -> Dict[str, Any]:
        """
        获取完整配置
        Returns:
            配置字典
        """
        if self._config is None:
            self.load_config()
        return self._config

    def get(self, key_path: str, default: Any = None) -> Any:
        """
        获取指定路径的配置值
        Args:
            key_path: 配置键路径，使用点号分隔，如 "model.deepseek.model_path"
            default: 默认值，如果配置不存在则返回
        Returns:
            配置值或默认值
        """
        if self._config is None:
            self.load_config()

        keys = key_path.split('.')
        value = self._config
        try:
            for key in keys:
                value = value[key]
            return value
        except (KeyError, TypeError):
            logger.warning(f"配置项不存在: {key_path}")
            return default

    def update(self, key_path: str, value: Any) -> bool:
        """
        更新配置值
        Args:
            key_path: 配置键路径
            value: 新的配置值
        Returns:
            是否更新成功
        """
        if self._config is None:
            self.load_config()

        keys = key_path.split('.')
        config = self._config
        try:
            for key in keys[:-1]:
                if key not in config:
                    config[key] = {}
                config = config[key]
            config[keys[-1]] = value
            return True
        except (KeyError, TypeError):
            logger.error(f"配置项更新失败: {key_path}")
            return False


# 创建全局配置实例
config_loader = ConfigLoader()


def get_config() -> Dict[str, Any]:
    """获取完整配置的便捷函数"""
    return config_loader.get_config()

def get(key_path: str, default: Any = None) -> Any:
    """获取指定路径配置的便捷函数"""
    return config_loader.get(key_path, default)

def update_config(key_path: str, value: Any) -> bool:
    """更新配置的便捷函数"""
    return config_loader.update(key_path, value)